﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PSMoveToAction : PSAction {
    protected PSMoveToAction() {}

    protected Vector3 target;
    protected Vector3 startpos;
    protected GameObject subject;

    public void Init(Vector3 target, float speed, GameObject subject, int identifier = 0, IPSActionCallback callback = null) {
        base.Init(identifier, callback);
        this.target = target;
        this.subject = subject;
        Rigidbody rb = subject.GetComponent<Rigidbody>();
        if (rb == null) {
            Debug.LogWarning("subject does not have a Rigidbody, now adding");
            rb = subject.AddComponent<Rigidbody>() as Rigidbody;
        }
        rb.isKinematic = false;

        startpos = subject.transform.position;
        rb.velocity = (target - startpos).normalized * speed;
    }

    public static PSMoveToAction GetPSAction() {
        PSMoveToAction action = ScriptableObject.CreateInstance<PSMoveToAction>();
        return action;
    }

    public override void FixedUpdate() {
        float a2 = (target - startpos).sqrMagnitude;
        float b2 = (target - subject.transform.position).sqrMagnitude;
        float c2 = (subject.transform.position - startpos).sqrMagnitude;
        if (a2 + b2 - c2 <= 1e-2f) {
            Rigidbody rb = subject.GetComponent<Rigidbody>();
            rb.velocity = Vector3.zero;
            SetOver(true);
            SendCompleteEvent(subject);
        }
    }
}
